package net.util;

import net.sf.cglib.beans.BeanGenerator;
import net.sf.cglib.beans.BeanMap;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class CglibBeanUtil {
    public Object object = null;
    /**
     * 属性map
     */
    public BeanMap beanMap = null;

    public CglibBeanUtil(){
        super();
    }

    @SuppressWarnings("unchecked")
    public CglibBeanUtil(Map properMap) {
             this.object = generateBean(properMap);
             this.beanMap= BeanMap.create(object);
    }

    /**
     * 给bean属性赋值
     */
    public void  setValue(String property,Object value){
        beanMap.put(property,value);
    }

    /**
     * 通过属性名得到属性值
     */
    public Object getValue(String property){
        return beanMap.get(property);
    }

    public Object getObject(){
        return this.object;
    }

    @SuppressWarnings("unchecked")
    private Object generateBean(Map propertyMap){
        BeanGenerator generator = new BeanGenerator();
        Set keyset = propertyMap.keySet();
        for(Iterator i=keyset.iterator();i.hasNext();){
            String key = (String)i.next();
            generator.addProperty(key,(Class)propertyMap.get(key));
        }
        return generator.create();
    }
}
